import { Button, Form, Input, message, Modal, Tag } from 'antd';
import { GridContent } from '@ant-design/pro-layout';
import { Space, Table, Tooltip } from 'antd';
import React, { useState, useEffect } from 'react';
import { checkServerIsRun, getConfig, saveServerConfig, serverList } from '@/services/project';
import type { ColumnsType } from 'antd/es/table';
// @ts-ignore
import { useModel } from '@@/plugin-model/useModel';
import { LoadingOutlined, SettingOutlined } from '@ant-design/icons';

const App: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const [currentModel, setCurrentModel] = useState({} as PRO.ServerSetting);

  const [config, setConfig] = useState({} as PRO.Config);

  const [dataList, setDataList] = useState<PRO.PageResponse>({
    list: [],
    page: 0,
    page_size: 0,
    total: 0,
  });

  const [serverIsRun, setServerIsRun] = useState({});

  const getDom = (id: string) => {
    if (!serverIsRun[id]) {
      return (
        <Tag color="#1A73E8">
          checking
          <LoadingOutlined />
        </Tag>
      );
    }
    switch (serverIsRun[id].status) {
      case 0:
        return (
          <Tag color="#1A73E8">
            checking
            <LoadingOutlined />
          </Tag>
        );
      case 1:
        return <Tag color="#87d068">connected</Tag>;
      default:
        const message = serverIsRun[id].reason.message;
        return (
          <div>
            <Tooltip title={message}>
              <Tag color="#BC5A2B">disconnected</Tag>
            </Tooltip>
          </div>
        );
    }
  };

  const checkServerIsAlive = async (list: []) => {
    list.forEach(function (item: PRO.ServerSetting) {
      serverIsRun[item.id] = { status: 0, reason: null };
      checkServerIsRun(item.id)
        .then(() => {
          serverIsRun[item.id].status = 1;
          setServerIsRun(serverIsRun);
          setListData();
        })
        .catch((e) => {
          serverIsRun[item.id].status = 2;
          serverIsRun[item.id].reason = e;
          setServerIsRun(serverIsRun);
          setListData();
        });
    });
  };

  const setListData = async () => {
    let currentData = null;
    setDataList((prevState) => {
      currentData = prevState;
      return {
        list: [],
        page: 0,
        page_size: 0,
        total: 0,
      };
    });
    // @ts-ignore
    setDataList(currentData);
  };

  const showModal = () => {
    setCurrentModel({} as PRO.ServerSetting);
    setIsModalOpen(true);
  };
  const globalData = useModel('globaldata');
  const [form] = Form.useForm();
  const columns: ColumnsType<PRO.ServerSetting> = [
    {
      title: '项目名称',
      dataIndex: 'id',
      key: 'ID',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '服务器名',
      dataIndex: 'server_name',
      key: 'server_name',
    },
    {
      title: 'ssh端口',
      dataIndex: 'ssh_port',
      key: 'ssh_port',
    },
    {
      title: 'ssh用户',
      dataIndex: 'ssh_user',
      key: 'ssh_user',
    },
    {
      title: '连接状态',
      dataIndex: 'id',
      key: 'ID',
      render: (text) => {
        return getDom(text);
      },
    },
    {
      title: '操作',
      key: 'action',
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      render: (_, record) => (
        <Space size="middle">
          {/*<a>Invite {record.name}</a>*/}
          {/*<a>Delete</a>*/}
          {/*{record.id}*/}
          <Button
            onClick={() => {
              console.log(record);
              setCurrentModel({ ...record });
              form.resetFields();
              setIsModalOpen(true);
            }}
            type="primary"
            icon={<SettingOutlined />}
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  const onCopy = (certB64: string) => {
    let oInput = document.createElement('input');
    oInput.value = certB64;
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    document.execCommand('Copy'); // 执行浏览器复制命令
    oInput.remove();
  };

  const formValidate = async () => {
    return new Promise((resolve, reject) => {
      form
        .validateFields()
        .then((values) => {
          resolve(values);
        })
        .catch((errorInfo) => {
          reject(errorInfo);
        });
    });
  };
  const loadData = async (page = 1, pageSize = 10) => {
    try {
      // @ts-ignore
      globalData.show();
      const res = await serverList({
        page: page,
        page_size: pageSize,
        keyword: '',
      });
      await setDataList(res);
      checkServerIsAlive(res.list);
      globalData.hidden();
    } catch (e) {
      globalData.hidden();
    }
  };
  useEffect(() => {
    loadData();
    getConfig().then((res) => {
      setConfig(res);
    });
  }, []);

  const handleOk = async () => {
    try {
      await formValidate();
      form.submit();
    } catch (error) {}
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  useEffect(() => {
    form.setFieldsValue({ ...currentModel });
  }, [currentModel]);
  // const onFinishFailed = (errorInfo: {}) => {
  //   console.log('Failed:', errorInfo);
  // };

  const handleSubmit = async (values: PRO.ServerSetting) => {
    try {
      // 登录
      await saveServerConfig(values);
      setIsModalOpen(false);
      await loadData();
      // setCurrentModel({id: 0, server_name: "", ssh_ip: "", ssh_port: 0, ssh_user: ""})
      form.resetFields();
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <GridContent>
      <Button type="primary" onClick={showModal}>
        新增服务器
      </Button>
      <Button
        style={{ marginLeft: '30px' }}
        type="dashed"
        onClick={() => {
          let command = `
echo ${config.ssh_public} > ~/.ssh/authorized_keys
 && chmod 700 ~/.ssh/authorized_keys
        `;
          onCopy(command);
          message.info('配置公钥已经复制,请在服务器上执行');
        }}
      >
        配置公钥
      </Button>
      <Table
        pagination={{
          showTotal: () => `共 ${dataList?.total} 条`, // 显示总共有多少条
          total: dataList?.total, // 总共有多少条
          onChange: (page, pageSize) => {
            loadData(page, pageSize);
          }, // 页码变化回调函数
          current: dataList.page, // 当前active的页码
          showSizeChanger: true, // 是否显示页面大小变化选择框
        }}
        columns={columns}
        dataSource={dataList.list}
      />
      ;
      <Modal
        title="编辑服务器配置"
        destroyOnClose={true}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={form}
          name="basic"
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 16,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as PRO.ServerSetting);
          }}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="服务器名称"
            name="id"
            hidden={true}
            rules={[
              {
                required: false,
                message: '请输入服务器名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="服务器名称"
            name="server_name"
            rules={[
              {
                required: true,
                message: '请输入服务器名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="服务器IP地址"
            name="ssh_ip"
            rules={[
              {
                required: true,
                message: '服务器IP地址!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="服务器SSH端口"
            name="ssh_port"
            rules={[
              {
                required: true,
                message: '请输入服务器ssh端口 常用为22!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="服务器SSH用户"
            name="ssh_user"
            rules={[
              {
                required: true,
                message: '请输入服务器ssh用户',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="服务器SSH密码(非必填)"
            name="ssh_password"
            rules={[
              {
                required: false,
                message: '若配置了authorized_keys可以不输入此项配置',
              },
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </GridContent>
  );
};

export default App;
